package com.ice.base.util;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * IO模块工具类
 */
@Slf4j
@Component
public class IOUtil {

    /**
     * 操作IO模块
     *
     * @param str
     */
    public void operIo(String ip, String port, String str) {
        System.out.println("调用IO模块，ip:" + ip + ",端口:" + port + ",命令:" + str);
        ThreadPoolExecutor threadPool = ThreadPoolUtil.getThreadPool();
        threadPool.submit(new Runnable() {
            @Override
            public void run() {
                Socket socket = null;
                DataOutputStream out = null;
                InputStream socketReader = null;
                try {
                    // 连接智能灯控制设备
                    socket = new Socket(InetAddress.getByName(ip), Integer.parseInt(port));
                    socket.setSoTimeout(5000);
                    // 得到Socket连接的输出流
                    out = new DataOutputStream(socket.getOutputStream());
                    // 向服务器发送Modbus指令
                    out.write(HexUtil.hex2Bytes(str));
                    // 立刻发送数据
                    out.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("IO模块操作失败");
                } finally {
                    try {
                        if (null != socket) {
                            socket.close();
                        }
                        if (null != socketReader) {
                            socketReader.close();
                        }
                        if (null != out) {
                            out.close();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }


        });

    }


}